package com.bdmc.smokesensor.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import com.bdmc.smokesensor.Utils.Msg;
import com.bdmc.smokesensor.Utils.MyException;
import com.bdmc.smokesensor.Utils.MyWebConfig;
import com.bdmc.smokesensor.Utils.ResultUtil;
import com.bdmc.smokesensor.entity.Smk_Buildings;
import com.bdmc.smokesensor.entity.Smk_Devices;
import com.bdmc.smokesensor.entity.Sys_Log;
import com.bdmc.smokesensor.entity.Sys_User;
import com.bdmc.smokesensor.services.Smk_BuildingsService;
import com.bdmc.smokesensor.services.Smk_DevicesService;
import com.bdmc.smokesensor.services.Smk_GroupCompanyService;
import com.bdmc.smokesensor.services.Sys_DepService;
import com.bdmc.smokesensor.services.Sys_UserService;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;


@RestController
@RequestMapping(value = "/devices", method = RequestMethod.POST)
public class Smk_DevicesController extends BaseController {

    @Autowired
    private Smk_DevicesService _devSvs;
    @Autowired
    private Sys_UserService _userSvs;
    @Autowired
    private Smk_BuildingsService _bdSvs;
    @Autowired
    private Smk_GroupCompanyService _gcSvs;
    @Autowired
    private Sys_DepService _depSvs;
    @Autowired
    private MyWebConfig _webconfig;

    @RequestMapping(value = "/list")
    public Msg listPageable(@RequestBody Map<String, Object> map) {
        int gc_id = Integer.valueOf(map.get("gc_id").toString());
        int dep_id = Integer.valueOf(map.get("dep_id").toString());
        String devName = map.get("devName").toString();
        int page = Integer.valueOf(map.get("page").toString());
        int rows = Integer.valueOf(map.get("rows").toString());
        if(dep_id==0){
            dep_id=Integer.valueOf(request.getAttribute("dep_id").toString());
        }
        return ResultUtil.success(_devSvs.findByPageable(dep_id, devName, gc_id, page, rows));
    }

    @RequestMapping(value = "/list1")
    public Msg listPageable1() {
        int user_id = Integer.valueOf(request.getAttribute("user_id").toString());
        return ResultUtil.success(_devSvs.findAll());
    }

    /**
     * 数据新增或更新，save方法可以执行添加也可以执行更新，如果需要执行持久化的实体存在主键值则更新数据，如果不存在则添加数据。
     */
    @RequestMapping(value = "/save")
    public Msg save(@RequestBody  Smk_Devices dev) {
/*         if(error.hasErrors()){
            return ResultUtil.error(-1, error.getFieldError().getDefaultMessage());
        } */
        String action = dev.getId()>0?"修改:":"新增:";
        if (dev.getSmkBuildingId() > 0) {
            Smk_Buildings sb = _bdSvs.findOneById(dev.getSmkBuildingId());
            dev.setDepartmentId(sb.getDepartmentId());
        } else {
            int user_id = Integer.valueOf(request.getAttribute("user_id").toString());
            Sys_User u = _userSvs.findOneById(user_id);
            dev.setDepartmentId(u.getDepartmentId());
        }
        try {
            Smk_Devices d = _devSvs.save(dev);
            if (d != null && d.getId() > 0) {
                Sys_Log log = new Sys_Log(getLoginName(), getLocalIp() , "设备管理", action+d.getDevName());
                _logSvs.save(log);
                return ResultUtil.success();
            } else {
                return ResultUtil.error(-1, "操作失败，请联系管理员。");
            }
        } catch (DataIntegrityViolationException e) {
            logger.error(e.getMessage());
            return ResultUtil.error(-1, "数据库已存在该设备。");
        }
        
         
    }

    /**
     * 删除设备信息，删除信息后返回剩余信息
     */
    @RequestMapping(value = "/delete")
    public Msg delete(@RequestBody Map<String, Integer> map) {
        int id = Integer.valueOf(map.get("id"));
        _devSvs.deleteById(id);
        Sys_Log log = new Sys_Log(getLoginName(), getLocalIp() , "设备管理", "删除："+id);
        _logSvs.save(log);
        return ResultUtil.success();
    }

    @RequestMapping(value = "/area_gc_bd")
    public Msg areaGcbd(@RequestBody Map<String, Boolean> map) {
        Boolean allData = Boolean.valueOf(map.get("allData"));
        int user_id = Integer.valueOf(request.getAttribute("user_id").toString());
        Sys_User u = _userSvs.findOneById(user_id);
        List<Map<String, Object>> deps = _depSvs.findByDepTypeAndTreeRootLike(2, u.getDepartmentId() + "");
        for (Map<String, Object> m1 : deps) {
            int depid = Integer.valueOf(m1.get("value").toString());
            List<Map<String, Object>> gcs = _gcSvs.findByDepId(depid);
            if (allData) {
                for (Map<String, Object> m2 : gcs) {
                    int gc_id = Integer.valueOf(m2.get("value").toString());
                    List<Map<String, Object>> bds = _bdSvs.findByGroupCompanyId(gc_id);
                    if (bds != null & bds.size() > 0)
                        m2.put("children", bds);
                }
            }

            if (gcs != null & gcs.size() > 0)
                m1.put("children", gcs);
        }
        return ResultUtil.success(deps);
    }

    @RequestMapping(value="import", method=RequestMethod.GET)
    public Msg importExcel(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        try {
            Map<String,Integer> map = _devSvs.batchImport(fileName, file);
            Sys_Log log = new Sys_Log(getLoginName(), getLocalIp() , "设备管理", "导入："+map.get("success").toString());
            _logSvs.save(log);
            return ResultUtil.success(map);
       } catch (MyException e) {
           return ResultUtil.error(-1, e.getContent());
       } catch (Exception e) {
        return ResultUtil.error(-1, "Excel格式不正确。");
        }
        
    }


    @RequestMapping(value = "export", method = RequestMethod.POST)
    public Msg downloadAllClassmate(@RequestBody Map<String,Object> map) throws IOException {
        int dep_id =Integer.valueOf(map.get("dep_id").toString());
        int gc_id =Integer.valueOf(map.get("gc_id").toString());
        String devName = map.get("devName").toString();
        if(dep_id==0){
            int user_id = Integer.valueOf(request.getAttribute("user_id").toString());
            Sys_User u = _userSvs.findOneById(user_id);
            dep_id=u.getDepartmentId();
        }

        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet("设备列表");
        List<Map<String,Object>> data = _devSvs.findForExcel(dep_id,devName,gc_id);
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");  
        String dateString = formatter.format(new Date()); 
        String fileName = "设备"+dateString+ ".xls";//设置要导出的文件的名字
        //新增数据行，并且设置单元格数据
        int rowNum = 1;
        String[] headers = { "设备名称", "设备型号", "imei","iccid","运营商","安装时间","安装地址","详细地址","联网单位","子单位","所属客户","客户手机"};
        //headers表示excel表中第一行的表头
        HSSFRow row = sheet.createRow(0);
        //在excel表中添加表头
        for(int i=0;i<headers.length;i++){
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            cell.setCellValue(text);
        }

        //在表中存放查询到的数据放入对应的列
        for (Map<String,Object> m : data) {
            HSSFRow row1 = sheet.createRow(rowNum);
            row1.createCell(0).setCellValue(m.get("devName")!=null?m.get("devName").toString():"");
            row1.createCell(1).setCellValue(m.get("devModel")!=null?m.get("devModel").toString():"");
            row1.createCell(2).setCellValue(m.get("imei")!=null?m.get("imei").toString():"");
            row1.createCell(3).setCellValue(m.get("iccid")!=null?m.get("iccid").toString():"");
            row1.createCell(4).setCellValue(m.get("operator")!=null?m.get("operator").toString():"");
            row1.createCell(5).setCellValue(m.get("installDate")!=null?m.get("installDate").toString():"");
            row1.createCell(6).setCellValue(m.get("bdAddr")!=null?m.get("bdAddr").toString():"");
            row1.createCell(7).setCellValue(m.get("installAddr")!=null?m.get("installAddr").toString():"");
            row1.createCell(8).setCellValue(m.get("groupName")!=null?m.get("groupName").toString():"");
            row1.createCell(9).setCellValue(m.get("bdName")!=null?m.get("bdName").toString():"");
            
            row1.createCell(10).setCellValue(m.get("managerName")!=null?m.get("managerName").toString():"");
            row1.createCell(11).setCellValue(m.get("managerMobile")!=null?m.get("managerMobile").toString():"");
            

            rowNum++;
        }
        try {
            File path = new File(_webconfig.getExportPath());
            if(!path.exists()){
                path.mkdir();
            }
            File f = new File(path.getAbsolutePath()+"/excel/",fileName);
            if(!f.getParentFile().exists()){
                f.getParentFile().mkdir();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(f);//指定路径与名字和格式
            workbook.write(fileOutputStream);//将数据写出去
            fileOutputStream.close();//关闭输出流
            return ResultUtil.success("/excel/"+fileName);
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtil.error(-1, e.getMessage());
        }
    }

    
}